// GA事件
const GAEvent = (eventname: string, gaAttrs = {}) => {
    // 确保只在客户端执行，并且 window.gtag 确实存在
    if (process.client && typeof window.gtag === 'function') {
        console.log('[GA]', eventname, gaAttrs)
        window.gtag("event", eventname, gaAttrs);
        
        // 等待 posthog 加载完成
        if (window.posthog && typeof window.posthog.capture === 'function') {
            window.posthog.capture(eventname, gaAttrs);
        }
    } else if (process.client) {
        console.warn('window.gtag function not found:', eventname);
    }
}

// TikTok事件
const TikTokEvent = (eventname: string, attrs: object = {}) => {
    // 确保只在客户端执行，并且 window.ttq 确实存在
    // 每次上报ClickButton，第3次另加上报CompletePayment
    if (!process.client) return
    if (!window?.ttq?.track) return
    // 自动插屏
    if (eventname === 'GAM_Inter_Click_Auto') {
        window.ttq.track('AddPaymentInfo')
    }
    // 旧：自动插屏+自动/手动页内广告
    // 新：GAM自动广告中的插屏、GAM/AFC手动广告中的display广告
    // （特殊说明：不包含APK站中手动display做锚定广告部分）
    if (eventname === 'GAM_IntIn_Click') {
        window.ttq.track('AddToCart');
    }
    if (eventname === 'AD_Click' || eventname === 'GAM_AD_Click_All') {
        try {
            const clickCount = Number(sessionStorage.getItem('_trackCount')) || 0;
            
            const activeElement = document.activeElement;
            const adContainer = activeElement?.closest("[data-ad-slot], [data-ad-ref]");
            if (!adContainer) return;
            const adSlot = adContainer.getAttribute("data-ad-slot") || "null";
            const adRef = adContainer.getAttribute("data-ad-ref") || "auto";
            const trackingPayload = {
                contents: [
                    {
                        content_id: adSlot,
                        content_name: adRef,
                        content_type: "ad",
                    }
                ],
                value: clickCount,
                currency: "USD"
            };

            const clickMap = clickCount % 3
            if (clickMap === 2) {
                window.ttq.track('CompletePayment', trackingPayload);
                console.log('[Tiktok]', 'CompletePayment', trackingPayload)
            }

            console.log('[Tiktok]', 'ClickButton', trackingPayload)
            window.ttq.track('ClickButton', trackingPayload);
        } catch (error) {
            console.warn('Error in BigoEvent:', error);
        }
    } else {
        console.warn('Bigo event tracking is only available in client-side environment');
    }
}

const BigoEvent = (eventname: string, attrs: object = {}, pid: string) => {
    if (!process.client) return
    // 确保只在客户端执行
    if (window?.bge && eventname === 'AD_Click') {
        try {
            const eventList = ['button', 'ec_detail_view','ec_add_cart'];
            const clickCount = Number(sessionStorage.getItem('_trackCount')) || 0;
            const eventName = eventList[clickCount % 3];
            
            const config = { ...attrs, configId: pid }
            console.log('[Bigo]', eventName, config)
            window.bge('event', eventName, config);
        } catch (error) {
            console.warn('Error in BigoEvent:', error);
        }
    } else {
        console.warn('Bigo event tracking is only available in client-side environment');
    }
}

// 日志事件分发
export const logEvent = (eventname: string, attrs: object = {}) => {
    // 获取 URL 参数（这个在服务器端和客户端都可以安全执行）
    const NuxtUrl = useRequestURL()
    const channel = NuxtUrl.searchParams.get('channel') || ''
    const network = NuxtUrl.searchParams.get('network') || ''
    const pid = NuxtUrl.searchParams.get('pid') || ''
    const gaAttrs = {
        ...attrs,
        Channel: channel,
        Network: network
    }
    // 调用辅助函数，它们内部会处理客户端检查
    GAEvent(eventname, gaAttrs)

    switch (network) {
        case 'tiktok':
            TikTokEvent(eventname, attrs)
            break
        case 'bigo':
            BigoEvent(eventname, attrs, pid)
            break
        default:
            break
    }
}


